package controllers

import (
	"project/jwt-prac/middlewares"
	"project/jwt-prac/models"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func LoginGet(c *gin.Context) {
	c.File("resources/login.html")
}

type myCustomClaims struct {
}

//POST;path:/login
func LoginPost(c *gin.Context) {
	var (
		userLogin models.UserLogin
		err       error
		user      models.User
	)
	//对用户登录的信息进行校验
	if err = c.ShouldBind(&userLogin); err != nil {
		c.JSON(400, gin.H{
			"msg":   "登录信息不符合规范",
			"error": err.Error(),
		})
		c.Abort()
		return
	}
	//通过数据库查询用户,并进行密码比对
	code, err := models.CheckUserLogin(&userLogin)
	if err != nil {
		c.JSON(code, gin.H{
			"msg": "认证失败，请检查密码",
		})
		c.Abort()
		return
	}

	user.LoginIp = c.ClientIP()
	user.LoginTime = time.Now()
	//更新用户表信息
	//主要是登录IP与登录时间
	code, err = models.UpdateUserDB(userLogin.Username, user)
	if err != nil {
		c.JSON(code, gin.H{
			"msg": err.Error(),
		})
		c.Abort()
		return
	}
	//创建jwt
	token, err := middlewares.JWTMan.Generate(jwt.StandardClaims{
		Audience:  userLogin.Username,
		ExpiresAt: time.Now().Unix() + middlewares.DefaultEXP,
		IssuedAt:  time.Now().Unix(),
		Issuer:    "haochen's site",
		NotBefore: time.Now().Unix() - 120,
		Subject:   "authorization",
	})
	if err != nil {
		//todo
		c.JSON(500, err)
		c.Abort()
		return
	}
	c.JSON(200, gin.H{
		"token": token,
	})
	//c.Redirect(302, "/test")
	//c.Request.URL.Query()
}
